package com.lanyun.aicorrectassistant.context;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户上下文对象
 *
 * @Author Jqcc
 * @Version 1.0
 * @Data 2025/3/4
 */
public class LoginContextHolder {

    /**
     * 全端都可使用 - 目前主要传递系统表用户id和角色
     */
    public static final String LOGIN_USER_HEADER = "login-user";

    public static final String LOGIN_USER_ROLE_HEADER = "login-user-role";

    public static final String LOGIN_USER_NAME_HEADER = "login-user-name";


    /**
     * miniApp端使用 - 目前主要传递小程序用户openid
     */
    public static final String MINI_APP_LOGIN_USER_HEADER = "mini-app-login-user";

    private static final InheritableThreadLocal<Map<String, Object>> INHERITABLE_THREAD_LOCAL
            = new InheritableThreadLocal<>();

    public static void set(String key, Object val) {
        Map<String, Object> map = getThreadLocalMap();
        map.put(key, val);
    }

    public static Object get(String key) {
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        return threadLocalMap.get(key);
    }

    public static String getLoginId() {
        Object value = getThreadLocalMap().get(LOGIN_USER_HEADER);
        return value != null ? value.toString() : null;
    }

    public static String getOpenid() {
        Object value = getThreadLocalMap().get(MINI_APP_LOGIN_USER_HEADER);
        return value != null ? value.toString() : null;
    }

    public static String getRole() {
        Object value = getThreadLocalMap().get(LOGIN_USER_ROLE_HEADER);
        return value != null ? value.toString() : null;
    }

    public static String getUserName() {
        Object value = getThreadLocalMap().get(LOGIN_USER_NAME_HEADER);
        return value != null ? value.toString() : null;
    }

    public static void remove() {
        INHERITABLE_THREAD_LOCAL.remove();
    }

    public static Map<String, Object> getThreadLocalMap() {
        Map<String, Object> map = INHERITABLE_THREAD_LOCAL.get();
        if (Objects.isNull(map)) {
            map = new ConcurrentHashMap<>();
            INHERITABLE_THREAD_LOCAL.set(map);
        }
        return map;
    }
}
